import { rootStore, makeLoggable, makeAutoObservable } from "@whzhuke/mobx"

import { arrayCommon, lsCommon } from "@whzhuke/common"
declare global {
  namespace globalContext {
    interface data {
      UserStore: UserStore
    }
  }
  namespace localStorageData {
    interface data {
      user: any | null
      menu: any
    }
  }
}

export class UserStore {
  constructor() {
    window['store']=this
    makeAutoObservable(this)
    makeLoggable(this)
  }
  open = false
  setOpen(open: boolean) {
    this.open = open
  }
  ready = false
  setReady(ready: boolean) {
    this.ready = ready
  }
  show = false
  setShow(show: boolean) {
    this.show = show
  }
  user: any | null = lsCommon.getItem("user")
  setUser(data: UserStore["user"]) {
    this.user = data

    data ? lsCommon.setItem("user", data) : lsCommon.removeItem("user")
  }
  menu: any = lsCommon.getItem("menu") || []
  setMenu(data: UserStore["menu"]) {
    this.menu = data
    lsCommon.setItem("menu", data)
  }

  get MenuTreeNode() {
    if (!this.menu) return []
    const tree = arrayCommon.doTree(this.menu!, "id", "parentId")
    const renderMenu = (list: typeof tree) => {
      return list
        .slice()
        .sort((prev: any, next: any) => (next.sort || next.id) - (prev.sort || prev.id))
        .map(item => {
          return {
            ...item,
            children: item.children?.length ? renderMenu(item.children) : undefined
          }
        })
    }
    return renderMenu(tree) as typeof tree
  }
}
export function initUserStore() {
  rootStore.UserStore = new UserStore()
}
